import { IUser } from "@/apis/types"
import { getUserInfo } from "@/apis/web/User"
import { IGlobalState } from "@/global/types"
import { useCookie } from "@/hooks/useCookie"
import { useCrypto } from "@/hooks/useCrypto"
import { useElLoading } from "@/hooks/useElLoading"
import { useElMessage } from "@/hooks/useElMessage"
import app from "@/main"
import store from "@/store"
import { isEmptyObj } from "@/utils/core"
import { ElMessage } from "element-plus"
import { RouteMeta, RouteRecordRaw, Router } from "vue-router"
import { asyncRoutes } from '../asyncRoutes'

export const filterAsyncRoutes = (routes: Array<RouteRecordRaw>, role: string): Array<RouteRecordRaw> => {
    return routes.filter(route => {
        if (!isEmptyObj(route.meta)) {
            const meta: RouteMeta = route.meta
            if (meta.roles.includes(role)) {
                return route
            }
        }
    })
}
export const promission = (router: Router) => {
    const whiteList = ["/login", "/errPage"] // 不重定向的白名单\
    router.beforeEach(async (to, from, next) => {
        const global: IGlobalState = app.config.globalProperties.$global

        const token = useCookie().getCookie(global.cookiesTokenName)

        // 用户未登录
        if (!token) {
            if (whiteList.includes(to.path)) {
                next()
            } else {
                ElMessage.error("您还未登录, 请先登录");
                next("/login")
            }
        } else {
            // 用户本地存在token且有效, 动态路由已加载过
            if (router.getRoutes().length > 3) {
                if (to.path === "/login") {
                    next("/home")
                } else if (to.path === '/admin') {
                    const loading = useElLoading().service(document.body, "正在加载后台系统界面，请稍后...")
                    const res = store.dispatch('admin/generateMenuRoutes', router.getRoutes());
                    if (res) {
                        store.commit("admin/userManagement/_getAndUpdateUserList")
                        loading.close()
                        next()
                    } else {
                        next("/errPage")
                    }
                } else if (!router.getRoutes().find(route => route.path === to.path)) {
                    next("/errPage")
                }
                next()
            } else {
                // 动态路由未加载
                const userInfo: IUser = await getUserInfo();
                console.log("用户信息已获取");

                userInfo.username = useCrypto().decrypt(userInfo.username)
                userInfo.password = useCrypto().decrypt(userInfo.password)

                const routes = filterAsyncRoutes(asyncRoutes, userInfo.role)
                console.log("动态路由已过滤")

                routes.forEach(route => router.addRoute(route))
                console.log("动态路由已添加")

                store.commit("home/frontHeader/_generateRoutes", { routes, role: userInfo.role })
                console.log("导航栏信息已生成")

                store.commit("user/_setAsyncRoutes", routes)
                store.commit("user/_getAndSetRootFilePath")
                store.commit("home/frontAside/streamControl/_initStreamState", userInfo.camera)
                store.commit('_getAndSetWebsiteInfo')


                if (routes.length) {
                    next({ ...to, replace: true })
                } else {
                    useElMessage().error("您没有查看页面的权限！")
                    next("/")
                }
            }
        }
    });
    router.afterEach(() => {
    })
}
